package com.rc.service.impl;

import com.rc.entity.GenDatasource;
import com.rc.entity.gencode.DbType;
import com.rc.entity.gencode.GenDataSource;
import com.rc.mapper.GenDatasourceMapper;
import com.rc.service.GenDatasourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * <p>
 * 数据源管理 服务实现类
 * </p>
 *
 * @author rc
 * @since 2025-04-12
 */
@Service
@AllArgsConstructor
public class GenDatasourceServiceImpl extends ServiceImpl<GenDatasourceMapper, GenDatasource> implements GenDatasourceService {

    private final DataSource dataSource;



    @Override
    public GenDataSource get(String datasourceId) {
        // 初始化配置信息
        GenDataSource info = null;
        if (StringUtils.isBlank(datasourceId)) {
            try {
                info = new GenDataSource(dataSource.getConnection());
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        } else {
            info = new GenDataSource(this.getById(datasourceId));
        }

        return info;
    }

    @Override
    public String getDatabaseProductName(String dataSourceId) {
        if (StringUtils.isBlank(dataSourceId)) {
            return DbType.MySQL.name();
        } else {
            return getById(dataSourceId).getDbType();
        }
    }
}
